import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:file_picker/file_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sensors_plus/sensors_plus.dart';

import '../../app_session.dart';
import '../utils/toast_util.dart';
import 'aliyun_oss.dart';

/// 资源选择结果
class ResourcePickerResult {
  final String? filePath;
  final String? errorMessage;
  final bool isSuccess;

  ResourcePickerResult({
    this.filePath,
    this.errorMessage,
    required this.isSuccess,
  });

  factory ResourcePickerResult.success(String filePath) {
    return ResourcePickerResult(filePath: filePath, isSuccess: true);
  }

  factory ResourcePickerResult.error(String errorMessage) {
    return ResourcePickerResult(errorMessage: errorMessage, isSuccess: false);
  }
}

/// 资源选择器BottomSheet
class ResourcePickerSheet {
  /// 显示资源选择弹窗
  static void show({
    required Function(ResourcePickerResult result) onResult,
    bool allowVideo = true,
    bool allowMultiple = false,
    bool allowFile = true,
  }) {
    showModalBottomSheet(
      context: Get.context!,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.r),
              topRight: Radius.circular(12.r),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 选项列表
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                child: Column(
                  children: [
                    // 拍照/拍摄
                    _buildOptionItem(
                      icon: Icons.camera_alt,
                      title: '拍照/拍摄'.tr,
                      subtitle: '使用相机拍照或录制视频'.tr,
                      onTap: () => _handleCameraPicker(onResult, allowVideo),
                    ),

                    // 相册
                    _buildOptionItem(
                      icon: Icons.photo_library,
                      title: '相册'.tr,
                      subtitle: '从相册选择照片或视频'.tr,
                      onTap: () => _handleGalleryPicker(
                        onResult,
                        allowVideo,
                        allowMultiple,
                      ),
                    ),

                    if (allowFile)
                      // 文件
                      _buildOptionItem(
                        icon: Icons.folder,
                        title: '文件'.tr,
                        subtitle: '从文件管理器选择文件'.tr,
                        onTap: () => _handleFilePicker(onResult),
                      ),


                    SizedBox(height: 16.h),

                    FilledButton(
                      style: FilledButton.styleFrom(
                        minimumSize: Size(0.8.sw, 40),
                      ),
                      onPressed: Get.back,
                      child: Text('取消'.tr),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 16.h),
            ],
          ),
        );
      },
    );
  }

  /// 构建选项项
  static Widget _buildOptionItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        child: Row(
          children: [
            Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Icon(icon, color: Colors.blue, size: 20.sp),
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 16.sp,
              color: Colors.grey.shade400,
            ),
          ],
        ),
      ),
    );
  }

  /// 处理相机选择
  static Future<void> _handleCameraPicker(
    Function(ResourcePickerResult result) onResult,
    bool allowVideo,
  ) async {
    try {
      // 检查相机权限
      final cameraStatus = await Permission.camera.request();
      if (cameraStatus != PermissionStatus.granted) {
        onResult(ResourcePickerResult.error('需要相机权限才能使用此功能'.tr));
        Get.back();
        return;
      }

      // 检查麦克风权限（如果需要录制视频）
      if (allowVideo) {
        final microphoneStatus = await Permission.microphone.request();
        if (microphoneStatus != PermissionStatus.granted) {
          onResult(ResourcePickerResult.error('需要麦克风权限才能录制视频'.tr));
          Get.back();
          return;
        }
      }

      // 配置相机选择器
      final CameraPickerConfig config = CameraPickerConfig(
        enableAudio: allowVideo,
        enableRecording: allowVideo,
        enableSetExposure: true,
        enableTapRecording: allowVideo,
        textDelegate: CameraPickerTextDelegate(),
        maximumRecordingDuration: const Duration(seconds: 60),
        resolutionPreset: ResolutionPreset.high,
      );

      // 打开相机
      final AssetEntity? result = await CameraPicker.pickFromCamera(
        Get.context!,
        pickerConfig: config,
      );

      Get.back();

      if (result != null) {
        final String? filePath = await result.file.then((file) => file?.path);
        if (filePath != null) {
          onResult(ResourcePickerResult.success(filePath));
        } else {
          onResult(ResourcePickerResult.error('获取文件路径失败'.tr));
        }
      } else {
        onResult(ResourcePickerResult.error('用户取消了操作'.tr));
      }
    } catch (e) {
      Get.back();
      onResult(ResourcePickerResult.error('相机操作失败: $e'.tr));
    }
  }

  /// 备用相机选择方案（使用image_picker）
  static Future<void> _handleCameraPickerFallback(
    Function(ResourcePickerResult result) onResult,
    bool allowVideo,
  ) async {
    try {
      // 这里可以添加使用image_picker的备用实现
      // 暂时返回错误，提示用户使用相册选择
      onResult(ResourcePickerResult.error('iOS相机功能暂时不可用，请使用相册选择'.tr));
    } catch (e) {
              onResult(ResourcePickerResult.error('备用相机方案失败: $e'.tr));
    }
  }

  /// 处理相册选择
  static Future<void> _handleGalleryPicker(
    Function(ResourcePickerResult result) onResult,
    bool allowVideo,
    bool allowMultiple,
  ) async {
    try {
      // 检查相册权限
      PermissionStatus photosStatus;
      if (Platform.isAndroid) {
        final androidInfo = await DeviceInfoPlugin().androidInfo;
        if (androidInfo.version.sdkInt <= 32) {
          photosStatus = await Permission.storage.request();
        } else {
          photosStatus = await Permission.photos.request();
        }
      } else if (Platform.isIOS) {
        photosStatus = await Permission.photos.request();
      } else {
        photosStatus = await Permission.photos.request();
      }
      if (photosStatus != PermissionStatus.granted) {
        onResult(ResourcePickerResult.error('需要相册权限才能使用此功能'.tr));
        Get.back();
        return;
      }

      // 配置相册选择器
      final AssetPickerConfig config = AssetPickerConfig(
        maxAssets: allowMultiple ? 9 : 1,
        requestType: allowVideo ? RequestType.common : RequestType.image,
        textDelegate: AssetPickerTextDelegate(),
        filterOptions: FilterOptionGroup()
          ..setOption(AssetType.image, const FilterOption(needTitle: false))
          ..setOption(AssetType.video, const FilterOption(needTitle: false)),
      );

      // 打开相册
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: config,
      );

      Get.back();

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final String? filePath = await asset.file?.then((file) => file?.path);
        if (filePath != null) {
          onResult(ResourcePickerResult.success(filePath));
        } else {
          onResult(ResourcePickerResult.error('获取文件路径失败'.tr));
        }
      } else {
        onResult(ResourcePickerResult.error('用户取消了操作'.tr));
      }
    } catch (e) {
      Get.back();
      onResult(ResourcePickerResult.error('相册操作失败: $e'.tr));
    }
  }

  /// 处理文件选择
  static Future<void> _handleFilePicker(
    Function(ResourcePickerResult result) onResult,
  ) async {
    try {
      // 打开文件选择器
      final FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.any,
        allowMultiple: false,
        withData: false,
        withReadStream: false,
      );

      Get.back();

      if (result != null && result.files.isNotEmpty) {
        final String? filePath = result.files.first.path;
        if (filePath != null) {
          onResult(ResourcePickerResult.success(filePath));
        } else {
          onResult(ResourcePickerResult.error('获取文件路径失败'.tr));
        }
      } else {
        onResult(ResourcePickerResult.error('用户取消了操作'.tr));
      }
    } catch (e) {
      Get.back();
      onResult(ResourcePickerResult.error('文件选择失败: $e'.tr));
    }
  }
}
